'use strict';
const db = uniCloud.database()
const collection = db.collection('message-list')
exports.main = async (event, context) => {
	if (event.type === 'today') {
		let result = await getToDay(event)
		return result
	}
	if (event.type === 'oneinfo') {
		let result = await getOneInfo(event)
		return result
	}
	if (event.type === 'history' || event.type === 'future') {
		let result = await getMoreInfo(event)
		return result
	}
};

//获取历史消息或者未来等待提醒消息
function getMoreInfo(event) {
	let time = new Date(Date.now() + (8 * 60 * 60 * 1000))
	let ltinfo = time.toLocaleDateString() + '  ' + time.toLocaleTimeString()
	const dbCmd = db.command
	uniCloud.logger.info(event)
	let {
		pageIndex = 1,
			pageSize = 10
	} = event
	return new Promise(async resolve => {
		const count = await collection.where({
			openid: event.openid,
			sendTime: event.type == 'history' ? dbCmd.lt(ltinfo) : dbCmd.gt(ltinfo)
		}).count()
		const result = await collection.where({
			openid: event.openid,
			sendTime: event.type == 'history' ? dbCmd.lt(ltinfo) : dbCmd.gt(ltinfo)
		}).skip((pageIndex - 1) * pageSize).limit(pageSize).orderBy("addTime", 'desc').get()

		try {
			let info = {
				success: true,
				list: result.data,
				total: count.total,
			}
			resolve(info)
		} catch (e) {
			let info = {
				success: false,
				list: [],
				total: 0,
			}
			resolve(info)
		}
	})
}

// 获取当天的信息
function getToDay(event) {
	return new Promise(async resolve => {
		let year = Number(event.year) < 10 ? `0${ Number(event.year)}` : event.year
		let month = Number(event.month) < 10 ? `0${event.month}` : event.month
		let day = Number(event.day) < 10 ? `0${event.day}` : event.day
		uniCloud.logger.info(day)
		const result = await collection.where({
			openid: event.openid,
			year: year.toString(),
			month: month.toString(),
			day: day.toString()
		}).orderBy("addTime", 'desc').get()
		resolve(result)
	})
}

function getOneInfo(event) {
	return new Promise(async resolve => {
		const result = await collection.where({
			openid: event.openid,
			_id: event.id
		}).get()
		resolve(result)
	})
}
